package com.wl156.activities.find;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import org.ksoap2.serialization.SoapObject;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.wl156.BaseActivity;
import com.wl156.MyApp;
import com.wl156.lite.R;
import com.wl156.activities.order.MyGoodInfo;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;
import com.wl156.widget.ProviceSelector;

public class FindCarMessage extends BaseActivity implements OnClickListener {

	private static final String TAG = null;

	private ProviceSelector mFromProviceSelector;
	private ProviceSelector mToProviceSelector;
	private Spinner mTruckType;
	private EditText mTruckTonnage;
	private EditText mTruckLength;
	private EditText mPhone;
	private EditText mCarNo;
	private TextView mSetOffDate;
	private Button mSelectSetOffDate;
	private Button mConfirm;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_find_car_message);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		mFromProviceSelector = (ProviceSelector) findViewById(R.id.provice_selector);
		mFromProviceSelector.setTitle("起点: ");
		mFromProviceSelector.setProviceRequried(true);
		mToProviceSelector = (ProviceSelector) findViewById(R.id.to_provice_selector);
		mToProviceSelector.setTitle("终点: ");

		mTruckType = (Spinner) findViewById(R.id.car_model);
		mTruckTonnage = (EditText) findViewById(R.id.weight);
		mTruckLength = (EditText) findViewById(R.id.length);
		mSetOffDate = (TextView) findViewById(R.id.sef_off_date_show);
		mSelectSetOffDate = (Button) findViewById(R.id.select_set_off_date);
		mSelectSetOffDate.setOnClickListener(this);
		mConfirm = (Button) findViewById(R.id.confirm);
		mConfirm.setOnClickListener(this);
		mPhone = (EditText) findViewById(R.id.phone);
		mCarNo = (EditText) findViewById(R.id.carNo);

		new StartTask().execute();
	}

	boolean mProgramStartFindResult = true;

	class StartTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(FindCarMessage.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (result instanceof Object[]) {
					Object[] values = (Object[]) result;

					SoapObject truckList = (SoapObject) values[0];
					// 03-01 22:24:43.300: D/(28205): result:
					// anyType{ArrayOfString=anyType{string=1; string=前四后八; };
					// ArrayOfString=anyType{string=2; string=高栏车; };
					// ArrayOfString=anyType{string=3; string=挂车; };
					// ArrayOfString=anyType{string=4; string=双桥车; };
					// ArrayOfString=anyType{string=5; string=前四后四; }; }, type:
					// SoapObject
					String[] trucks = new String[truckList.getPropertyCount()];
					for (int i = 0; i < truckList.getPropertyCount(); i++) {
						SoapObject truck = (SoapObject) truckList
								.getProperty(i);
						trucks[i] = truck.getPropertyAsString(1);
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							FindCarMessage.this,
							R.layout.item_simple_dropdown_1line, trucks);
					mTruckType.setAdapter(adapter);

					SoapObject myCurrentPlace = (SoapObject) values[1];
					String lv1 = myCurrentPlace.getProperty(0).toString();
					String lv2 = myCurrentPlace.getProperty(1).toString();
					String lv3 = myCurrentPlace.getProperty(2).toString();
					mFromProviceSelector.setProvice(lv1);
					mFromProviceSelector.setCity(lv2);
					// mFromProviceSelector.setRegion(lv3);

					if (!getIntent().getBooleanExtra("isReturn", false)) {
						mProgramStartFindResult = true;
						mConfirm.performClick();
					} else {
						mProgramStartFindResult = false;
					}
				} else {
					AlertDialog.Builder builder = new Builder(
							FindCarMessage.this);
					builder.setMessage("网络请求超时！");
					builder.setPositiveButton("重试",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new StartTask().execute();
								}
							});
					builder.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							});
					builder.show();
				}
			} catch (Exception e) {
				Toast.makeText(FindCarMessage.this, "获取信息失败，请稍候再试",
						Toast.LENGTH_LONG).show();
			}

			mDialog.dismiss();
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				Object[] values = new Object[2];
				values[0] = mWebServiceClient.commomGetTruckList(mCertificate);
				values[1] = mWebServiceClient
						.commonGetMyCurrentPlace(mCertificate);
				return values;
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			final String startLocationLv1 = mFromProviceSelector.getProvice();
			final String startLocationLv2 = mFromProviceSelector.getCity();
			final String startLocationLv3 = mFromProviceSelector.getRegion();
			final String endLocationLv1 = mToProviceSelector.getProvice();
			final String endLocationLv2 = mToProviceSelector.getCity();
			final String endLocationLv3 = mToProviceSelector.getRegion();
			String truckType = mTruckType.getSelectedItem().toString();
			String truckTonnage = mTruckTonnage.getText().toString();
			String truckTonnageSymBol = "";
			String truckLength = mTruckLength.getText().toString();
			String truckLengthSymbol = "";
			String setOffDate = "";
			String setOffDateSymbol = "";

			if (TextUtils.isEmpty(startLocationLv1)) {
				Toast.makeText(FindCarMessage.this, "请填写相应字段",
						Toast.LENGTH_LONG).show();
				return;
			}
			Intent intent = new Intent(this, FindCarMessageResult.class);
			intent.putExtras(getIntent());
			intent.putExtra("startLocationLv1", startLocationLv1);
			intent.putExtra("startLocationLv2", startLocationLv2);
			intent.putExtra("startLocationLv3", startLocationLv3);
			intent.putExtra("endLocationLv1", endLocationLv1);
			intent.putExtra("endLocationLv2", endLocationLv2);
			intent.putExtra("endLocationLv3", endLocationLv3);
			intent.putExtra("truckType", truckType);
			intent.putExtra("truckTonnage", truckTonnage);
			intent.putExtra("truckTonnageSymBol", truckTonnageSymBol);
			intent.putExtra("truckLength", truckLength);
			intent.putExtra("truckLengthSymbol", truckLengthSymbol);
			intent.putExtra("setOffDate", setOffDate);
			intent.putExtra("setOffDateSymbol", setOffDateSymbol);
			intent.putExtra("phone", mPhone.getText().toString());
			intent.putExtra("carNo", mCarNo.getText().toString());
			intent.putExtra("mProgramStartFindResult", mProgramStartFindResult);
			startActivity(intent);
			finish();
			break;
		case R.id.select_set_off_date:
			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int monthOfYear = c.get(Calendar.MONTH);
			int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);

			DatePickerDialog datePicker = new DatePickerDialog(this,
					new OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							Date date = new Date(year - 1900, monthOfYear,
									dayOfMonth);
							mSelectSetOffDate
									.setText(WebServiceClient.sDateFormat
											.format(date));
							mSetOffDate.setText(WebServiceClient.sDateFormat
									.format(date));
						}
					}, year, monthOfYear, dayOfMonth);
			datePicker.show();
			break;
		}
	}
}
